package com.server.commons.security.Aspect;


import com.server.model.all.constant.token.TokenConstant;
import com.server.common.code.error.InsideException;
import com.server.common.code.utils.GsonUtils;
import com.server.common.code.utils.UserUtils;
import com.server.common.code.vo.LoginVo;
import com.server.common.security.code.SecurityUtils;
import com.server.common.security.code.anntation.Inside;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.lang.reflect.Method;

@Aspect
@Component
public class InsideAspect {

    @Around("@annotation(com.server.common.security.code.anntation.Inside)")
    public Object around(ProceedingJoinPoint point) throws Throwable {

        Signature signature = point.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();
        Inside inside = method.getAnnotation(Inside.class);

        String tokenJsonData = SecurityUtils.getHeader(TokenConstant.TOKEN_JSON_DATA);

        LoginVo loginVo = GsonUtils.getGson().fromJson(tokenJsonData,LoginVo.class);
        if (ObjectUtils.isEmpty(loginVo)) {
            throw new InsideException();
        }

        //内部接口只能admin使用
        if(ObjectUtils.isEmpty(inside) && UserUtils.haveAdmin(loginVo.getRoleId())){
            throw new InsideException();
        }

        return point.proceed();
    }
}
